package com.example.foodisimportant.LoginActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.foodisimportant.Network.NetworkSettings;
import com.example.foodisimportant.Network.LoginNetworkThread;
import com.example.foodisimportant.PersonalInformationActivity.PersonalInformationActivity;
import com.example.foodisimportant.R;
import com.example.foodisimportant.RegisterActivity.RegisterTest;
import com.example.foodisimportant.Body.ResponseBody;
import com.example.foodisimportant.StudentViewActivity.StudentViewActivity;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.concurrent.FutureTask;

public class LoginTest extends AppCompatActivity {
    private Button mBtnLogin;
    private TextView mRegister;
    private EditText mUsername;
    private EditText mPassward;
    private CheckBox mRememberPwd;
    private String Username,Passward;
    private SharedPreferences preferences;//用来进行数据的存储和读取
    private SharedPreferences.Editor editor;
    private Object mobject;

    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        saveData();

        //登录跳转
        mBtnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        //对应值
                        Username=mUsername.getText().toString();
                        Passward=mPassward.getText().toString();
                       //存放登录信息
                        if(mRememberPwd.isChecked()){//如果选择保存用户名
                            editor.putString("userName",Username);
                            editor.putString("userPassword",Passward);
                            editor.commit();//提交数据
                        }else{//如果未选择保存用户名
                            editor.remove("userName");//删除用户名
                            editor.remove("userPassword");//删除用户名
                            editor.commit();//提交数据(每次更改都需要提交)
                        }
                        //判断输入是否为空
                        if(Username.isEmpty() || Passward.isEmpty()){
                            //解决在子线程中调用Toast的异常情况处理
                            Toast.makeText(LoginTest.this, "请输入正确的用户名/账号和密码！", Toast.LENGTH_SHORT).show();

                        }else {
                            //提取记住密码的值
                            FutureTask<String> signInTask = new FutureTask<>(new LoginNetworkThread(Username,Passward,NetworkSettings.SIGN_IN));
                            Thread thread =new Thread(signInTask);
                            thread.start();
                            try{
                                mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
                                ResponseBody body = mapper.readValue(signInTask.get(), ResponseBody.class);
                                mobject=body.getData();
                                if(body.getCode() == 1){
                                    Toast.makeText(getApplicationContext(),body.getMsg()+"登录成功",Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(LoginTest.this, StudentViewActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("number",mUsername.getText().toString());
                                    bundle.putString("password",mPassward.getText().toString());
                                    intent.putExtras(bundle);
                                    finish();
                                    startActivity(intent);
                                }else {
                                    Toast.makeText(getApplicationContext(),"登录失败",Toast.LENGTH_SHORT).show();
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                        Looper.loop();
                    }
                }).start();
            }
        });
        //注册跳转
        mRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent= new Intent(LoginTest.this, RegisterTest.class);//跳转到注册界面
                startActivity(intent);
            }
        });
    }

    private void init() {
        //找到控件
        mBtnLogin = findViewById(R.id.btn_lg);
        mRegister=findViewById(R.id.tv_rg);
        mUsername=findViewById(R.id.et1);
        mPassward=findViewById(R.id.et2);
        mRememberPwd=findViewById(R.id.cb1);
    }

    private void saveData() {
        //获得SharedPreferences对象
        preferences=getSharedPreferences("userInfo",MODE_PRIVATE);//将内容存放到名为userInfo的文档内
        //获得SharedPreferences.Editor对象
        editor=preferences.edit();
        String name=preferences.getString("userName",null);//获取用户名
        String pwd=preferences.getString("userPassword",null);//获取用户名
        if(name.equals("")){//如果name为空，代表未选择保存用户名
            mRememberPwd.setChecked(false);//不勾选
        }else{
            mRememberPwd.setChecked(true);
            mUsername.setText(name);//将读取到的name值赋值到EditText中
            mPassward.setText(pwd);//将读取到的password赋值
        }
    }

}
